package com.douyin.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
@Service
public class DouyinParseService {

    @Autowired
    private ThirdPartyApiService thirdPartyApiService;

    // 禁用的浏览器相关服务 - 改用第三方API
    // @Autowired
    // private PlaywrightParserService playwrightParserService;
    // @Autowired
    // private DouyinHtmlParserService htmlParserService;
    // @Autowired
    // private SeleniumDouyinParserService seleniumDouyinParserService;
    // @Autowired
    // private DouyinTokenService tokenService;

    @Value("${app.douyin.user-agent}")
    private String userAgent;

    @Value("${app.douyin.parse-timeout}")
    private int timeout;

    @Value("${app.douyin.retry-times}")
    private int retryTimes;

    // 抖音链接匹配规则
    private static final Pattern DOUYIN_URL_PATTERN =
        Pattern.compile("(https?://)?(www\\.)?(douyin|iesdouyin)\\.com");

    private static final Pattern DOUYIN_SHORT_URL_PATTERN =
        Pattern.compile("(https?://)?(v\\.douyin\\.com)");

    /**
     * 主要解析方法 - 使用第三方API
     */
    public Map<String, Object> parseDouyinUrl(String url) {
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("🚀 开始使用第三方API解析抖音链接: {}", url);
            
            // 使用第三方API解析
            Map<String, Object> parseResult = thirdPartyApiService.parseFromShareText(url);

            if (parseResult == null) {
                result.put("success", false);
                result.put("message", "第三方API解析返回空结果");
                result.put("parseMethod", "third-party-api");
                return result;
            }

            // 检查API解析是否成功
            Boolean apiSuccess = (Boolean) parseResult.get("success");
            if (apiSuccess == null || !apiSuccess) {
                result.put("success", false);
                result.put("message", parseResult.get("error") != null ? parseResult.get("error").toString() : "第三方API解析失败");
                result.put("parseMethod", "third-party-api");
                result.put("originalText", parseResult.get("originalText"));
                result.put("extractedUrl", parseResult.get("extractedUrl"));
                return result;
            }

            // 构造返回结果 - 确保success字段在顶层
            result.put("success", true);
            result.put("message", "第三方API解析成功");
            result.put("parseMethod", "third-party-api");
            
            // 将解析结果的主要字段提取到顶层，确保前端能正确识别
            result.put("fileType", parseResult.get("fileType"));
            result.put("title", parseResult.get("title"));
            result.put("cover", parseResult.get("cover"));
            result.put("author", parseResult.get("author"));
            result.put("originalText", parseResult.get("originalText"));
            result.put("extractedUrl", parseResult.get("extractedUrl"));
            result.put("originalUrl", parseResult.get("originalUrl"));
            
            // 根据类型设置媒体链接
            String fileType = (String) parseResult.get("fileType");
            if ("video".equals(fileType)) {
                result.put("videoUrl", parseResult.get("videoUrl"));
            } else if ("image".equals(fileType)) {
                result.put("images", parseResult.get("images"));
            }
            
            // 保留data字段供其他地方使用
            result.put("data", parseResult);
            result.put("apiResponse", parseResult.get("apiResponse"));

            log.info("✅ 第三方API解析成功");
            return result;

        } catch (Exception e) {
            log.error("❌ 第三方API解析失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "第三方API解析失败: " + e.getMessage());
            result.put("parseMethod", "third-party-api");
            return result;
        }
    }

    /**
     * 验证是否为有效的抖音链接
     */
    public boolean isValidDouyinUrl(String url) {
        if (url == null || url.trim().isEmpty()) {
            return false;
        }

        // 检查是否包含抖音相关域名
        return url.contains("douyin.com") ||
               url.contains("iesdouyin.com") ||
               DOUYIN_URL_PATTERN.matcher(url).find() ||
               DOUYIN_SHORT_URL_PATTERN.matcher(url).find();
    }
}